/*
 * @Author: Drc
 * @Date: 2020-11-17 12:04:44
 * @LastEditTime: 2021-09-24 11:28:59
 * @LastEditors: Drc
 */

import React, {useLayoutEffect, useRef, useState} from 'react'
import {Animated, Easing, View} from 'react-native'
import {useSelector} from 'react-redux'
import {RouteProps} from '@path/navigation/controller'
import {RootState} from '@path/redux'
import RNWebView, {WebViewProps} from 'react-native-webview'
import Theme from '@path/config/theme'
import _ from 'lodash'
export interface WebViewParams extends WebViewProps {
  title?: string
}
const WebView = (props: RouteProps<'WebView'>) => {
  const global = useSelector(
    (state: RootState) => state.global,
    (prev, next) => _.isEqual(prev, next),
  )

  const {title, source} = props.route?.params

  useLayoutEffect(() => {
    props.navigation.setOptions({
      title: title,
    })
  }, [props.navigation, global, title])

  useLayoutEffect(() => {
    props.navigation.setOptions({
      title: title,
    })
  }, [props.navigation, global, title])

  const [isLoadEnd, set_isLoadEnd] = useState(false)

  const progressAnim = useRef(new Animated.Value(0))

  return (
    <View style={{flex: 1}}>
      <RNWebView
        source={{headers: {'Cache-Control': 'no-cache'}, ...source}}
        domStorageEnabled
        onLoad={(e) => {
          //设置标题
          if (!title) {
            props.navigation.setOptions({
              title: e.nativeEvent?.title || '',
            })
          }
        }}
        onLoadProgress={(e) => {
          let progress = e.nativeEvent.progress
          Animated.timing(progressAnim.current, {
            toValue: progress,
            duration: 400,
            useNativeDriver: false,
            easing: Easing.ease,
          }).start()
        }}
        onLoadStart={() => {
          set_isLoadEnd(false)
        }}
        onLoadEnd={() => {
          set_isLoadEnd(true)
        }}
        decelerationRate="normal"
        originWhitelist={['*']}
        scalesPageToFit={false}
        automaticallyAdjustContentInsets={false}
        javaScriptEnabled={true}
        androidHardwareAccelerationDisabled
      />
      {isLoadEnd ? null : (
        <View style={{height: 2, position: 'absolute', width: '100%', flexDirection: 'row'}}>
          <Animated.View
            style={{
              height: '100%',
              flexDirection: 'row',
              flex: progressAnim.current,
              backgroundColor: Theme.getThemeColor('theme'),
            }}
          />
        </View>
      )}
    </View>
  )
}
export default WebView
